<?php

namespace common\jobs;

use Yii;
use common\helpers\ArrayHelper;
use common\models\annual\TicketAnnual;
use common\models\annual\TicketAnnualBleacher;

/**
 * 生成看台年票队列任务
 * Class CreateAnnualTicketJob.
 */
class CreateAnnualTicketJob extends BaseRetryableJob {

    public $id;

    /**
     * @param \yii\queue\Queue $queue which pushed and is handling the job
     */
    public function execute($queue) {
        if (!$this->id) {
            return false;
        }
        $bleacher = TicketAnnualBleacher::findOrFail($this->id);
        $amount = $bleacher->amount;
        $annuals = count($bleacher->annuals);
        if ($annuals >= $amount) {
            return true;
        }
        $annual = new TicketAnnual();
        $annual->attributes = [
            'round_id' => $bleacher->round_id,
            'bleacher_id' => $bleacher->id,
            'type_id' => $bleacher->type_id,
            'price' => $bleacher->price,
        ];
        $pagesize = 32;
        $size = min($pagesize, $amount - $annuals);
        for ($i = 0; $i < $size; $i++) {
            $_model = clone $annual;
            $_model->buildTicket($annuals + $i + 1);
            if (!$_model->save()) {
                Yii::error($_model->getErrors(), __CLASS__ . __METHOD__);
                return false;
            }
        }
        if ($amount - $annuals - $size > 0) {
            Yii::$app->queue->delay(1)->push(new \common\jobs\CreateAnnualTicketJob([
                'id' => $this->id,
            ]));
        }
        return true;
    }

    /**
     * @inheritdoc
     */
    public function getTtr() {
        return 1;
    }

    /**
     * @inheritdoc
     */
    public function canRetry($attempt, $error) {
        return $attempt < 3;
    }

}
